<template>
  <a-modal v-model:visible="visible" :title="title" :mask-closable="false" :esc-to-close="false" draggable
    :width="width >= 600 ? 600 : '100%'" @before-ok="save" @close="reset">
    <GiForm ref="formRef" v-model="form" :options="options" :columns="columns" />
  </a-modal>
</template>

<script setup lang="ts">
import { Message } from '@arco-design/web-vue'
import { useWindowSize } from '@vueuse/core'
import { useResetReactive } from '@/hooks'
import { useDict } from '@/hooks/app'
import { addTestLog, getTestLog, updateTestLog } from '@/apis/task/testLog'
import { type Columns, GiForm, type Options } from '@/components/GiForm'

const emit = defineEmits<{
  (e: 'save-success'): void
}>()

const { width } = useWindowSize()

const dataId = ref('')
const visible = ref(false)
const isUpdate = computed(() => !!dataId.value)
const title = computed(() => (isUpdate.value ? '修改试验工作量' : '新增试验工作量'))
const formRef = ref<InstanceType<typeof GiForm>>()
const { test_register_status, fault_status } = useDict('test_register_status', 'fault_status')

const options: Options = {
  form: { size: 'large' },
  btns: { hide: true },
}

const [form, resetForm] = useResetReactive({
  // todo 待补充
})

const columns: Columns = reactive([
  {
    label: '加班时数',
    field: 'overtimeHour',
    type: 'input-number', 
    rules: [{ required: true, message: '请输入加班时数' }]
  },
  {
    label: '登记项目',
    field: 'registerStatus',
    type: 'select', 
    options: test_register_status,
    rules: [{ required: true, message: '请输入登记项目' }]
  },
  {
    label: '试验情况简述',
    field: 'testDescription',
    type: 'textarea',
  },
  {
    label: '发动机是否故障',
    field: 'isFault',
    type: 'select', 
    options: fault_status,
    rules: [{ required: true, message: '请输入发动机是否故障' }]
  },
  {
    label: '故障描述',
    field: 'faultDescription',
    type: 'textarea',
  },
  {
    label: '试验名称',
    field: 'name',
    type: 'input',
    rules: [{ required: true, message: '请输入试验名称' }]
  },
  {
    label: '试验任务ID',
    field: 'taskId',
    type: 'input',
    rules: [{ required: true, message: '请输入试验任务ID' }]
  },
])

// 重置
const reset = () => {
  formRef.value?.formRef?.resetFields()
  resetForm()
}

// 保存
const save = async () => {
  try {
    const isInvalid = await formRef.value?.formRef?.validate()
    if (isInvalid) return false
    if (isUpdate.value) {
      await updateTestLog(form, dataId.value)
      Message.success('修改成功')
    } else {
      await addTestLog(form)
      Message.success('新增成功')
    }
    emit('save-success')
    return true
  } catch (error) {
    return false
  }
}

// 新增
const onAdd = async () => {
  reset()
  dataId.value = ''
  visible.value = true
}

// 修改
const onUpdate = async (id: string) => {
  reset()
  dataId.value = id
  const { data } = await getTestLog(id)
  Object.assign(form, data)
  visible.value = true
}

defineExpose({ onAdd, onUpdate })
</script>

<style scoped lang="scss"></style>
